package model

import (
	"gorm.io/datatypes"
	"gorm.io/gorm"
	"time"
	"unicode/utf8"
)

type FileTask struct {
	ID          uint64         `gorm:"column:id;primaryKey;autoIncrement;comment:PK"`
	TaskID      string         `gorm:"column:task_id;type:varchar(128);not null;default:'';comment:文件任务id"`
	TaskName    string         `gorm:"column:task_name;type:varchar(128);not null;default:'';comment:文件名"`
	TaskType    int8           `gorm:"column:task_type;type:tinyint;not null;default:0;comment:文件任务类型"`
	TaskStatus  int8           `gorm:"column:task_status;type:tinyint;not null;default:0;comment:文件任务状态"`
	SourceFiles datatypes.JSON `gorm:"column:source_files;comment:源文件"`
	TargetFiles datatypes.JSON `gorm:"column:target_files;comment:处理后的文件"`
	UnionId     string         `gorm:"column:union_id;type:varchar(128);not null;comment:用户id"`
	OutputLog   string         `gorm:"column:output_log;type:text;comment:输出日志"`
	CreatedAt   time.Time      `gorm:"column:created_at;type:timestamp;not null;default:CURRENT_TIMESTAMP;comment:User information create time"`
	UpdatedAt   time.Time      `gorm:"column:updated_at;type:timestamp;not null;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;comment:User information update time"`
	DeletedAt   gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp;index;comment:User information delete time"`
}

func (ft *FileTask) TableName() string {
	return "t_file_task"
}

const maxTextLen = 21800

// BeforeSave 在保存前自动截断超长日志（最大支持21844个字符，保留安全余量）
func (ft *FileTask) BeforeSave(tx *gorm.DB) error { // 保留44字符余量用于添加截断标记
	if utf8.RuneCountInString(ft.OutputLog) > maxTextLen {
		// 安全截断多字节字符
		ft.OutputLog = truncateString(ft.OutputLog, maxTextLen) + "...[已截断]"
	}
	return nil
}

func (ft *FileTask) BeforeCreate(tx *gorm.DB) error {
	if utf8.RuneCountInString(ft.OutputLog) > maxTextLen {
		// 安全截断多字节字符
		ft.OutputLog = truncateString(ft.OutputLog, maxTextLen) + "...[已截断]"
	}
	return nil
}

func (ft *FileTask) BeforeUpdate(tx *gorm.DB) error {
	if utf8.RuneCountInString(ft.OutputLog) > maxTextLen {
		// 安全截断多字节字符
		ft.OutputLog = truncateString(ft.OutputLog, maxTextLen) + "...[已截断]"
	}
	return nil
}

// 安全截断字符串（处理多字节字符）
func truncateString(s string, maxLen int) string {
	if len(s) <= maxLen {
		return s
	}

	var size int
	for i := 0; i < maxLen; {
		_, n := utf8.DecodeRuneInString(s[i:])
		if i+n > maxLen {
			break
		}
		size = i + n
		i += n
	}
	return s[:size]
}
